package net.bblbs.zhongrx.service;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import net.bblbs.zhongrx.DynamicPhotoFragment;
import net.bblbs.zhongrx.LoginActivity;
import net.bblbs.zhongrx.Photo1Fragment;
import net.bblbs.zhongrx.Photo2Fragment;
import net.bblbs.zhongrx.Photo3Fragment;
import net.bblbs.zhongrx.Photo4Fragment;
import net.bblbs.zhongrx.R;
import net.bblbs.zhongrx.SectionListActivity;
import net.bblbs.zhongrx.SelectActivity;
import net.bblbs.zhongrx.util.FileStoreUtil;
import net.bblbs.zhongrx.util.HttpCallbackListener;
import net.bblbs.zhongrx.util.HttpRequest;

import java.util.List;

/**
 * Created by qxb on 2017/3/21.
 */

public class UploadService extends Service {

  private static final String TAG = "ZRX_UPLOADSERVICE";

  int totalAttach=0;

  int finishAttach=0;

  String personId="";

  SectionListActivity sectionListActivity;

  private UploadTask[] uploadTasks;
  private UpdateTask  updateTask;

  private UploadListener listener = new UploadListener() {

    @Override
    public void onFinish() {
      finishAttach ++;

      if (finishAttach == totalAttach) {
        Log.d(TAG, "on all Finish: "+ finishAttach);

        for(UploadTask task : uploadTasks){
          task = null;
        }
        updateTask = null;


        stopForeground(true);
//        getNotificationManager().notify(1, getNotification("上传成功", -1));

        Toast.makeText(UploadService.this, "上传成功", Toast.LENGTH_SHORT).show();
        tearDown();


      }else {

        Log.d(TAG, "onFinish: "+ finishAttach);
        int progress = (int) (finishAttach  * 100 / totalAttach );
        getNotificationManager().notify(1, getNotification("上传(" + finishAttach + "/" +totalAttach +")", progress));
        Toast.makeText(UploadService.this, "上传(" + finishAttach + "/" +totalAttach +")" , Toast.LENGTH_SHORT).show();
      }
    }

    @Override
    public void onFailed() {
      for(UploadTask task : uploadTasks){
        task = null;
      }
      stopForeground(true);
      getNotificationManager().notify(1, getNotification("Upload Failed", -1));
      Toast.makeText(UploadService.this, "Upload Failed", Toast.LENGTH_SHORT).show();
    }

    public void tearDown(){
      HttpRequest.postWithCallback(getString(R.string.ws_base_url), "/tango/toStateExaming/" + personId, "", new HttpCallbackListener() {
        @Override
        public void onFinish(String response) {
          Log.d(TAG, "onFinish: ");

//          FileStoreUtil.deleteFiles(personId, UploadService.this);
//
//          SharedPreferences pref1 = UploadService.this.getSharedPreferences(Photo1Fragment.SP_NAME, Context.MODE_PRIVATE);
//          pref1.edit().remove(Photo1Fragment.SP_NAME + "_"+ personId).commit();
//
//          SharedPreferences pref2 = UploadService.this.getSharedPreferences(Photo2Fragment.SP_NAME, Context.MODE_PRIVATE);
//          pref2.edit().remove(Photo2Fragment.SP_NAME + "_"+ personId).commit();
//
//          SharedPreferences pref3 = UploadService.this.getSharedPreferences(Photo3Fragment.SP_NAME, Context.MODE_PRIVATE);
//          pref3.edit().remove(Photo3Fragment.SP_NAME + "_"+ personId).commit();
//
//          SharedPreferences pref4 = UploadService.this.getSharedPreferences(Photo4Fragment.SP_NAME, Context.MODE_PRIVATE);
//          pref4.edit().remove(Photo4Fragment.SP_NAME + "_"+ personId).commit();
//
//          SharedPreferences pref5 = UploadService.this.getSharedPreferences(DynamicPhotoFragment.SP_NAME, Context.MODE_PRIVATE);
//          pref5.edit().remove(DynamicPhotoFragment.SP_NAME + "_"+ personId).commit();

          SharedPreferences prefInfo = UploadService.this.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);
          prefInfo.edit().remove("dynamic_info_"+ personId).commit();


          Intent intent = new Intent();
          sectionListActivity.setResult(Activity.RESULT_OK, intent);
          sectionListActivity.finish();
//          Intent intent = new Intent(UploadService.this, SelectActivity.class);
//          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//          startActivity(intent);

        }

        @Override
        public void onError(Exception e) {
          Log.d(TAG, "onError: ");
        }
      });

    }

  };

  private UploadBinder mBinder = new UploadBinder();

  @Override
  public IBinder onBind(Intent intent) {
    return mBinder;
  }

  public class UploadBinder extends Binder {

    public void startUpload(List<String> fileNames, List<String> fileUrls, String pId, SectionListActivity sectionList) {

      startForeground(1, getNotification("开始上传...", -1));
      Toast.makeText(UploadService.this, "开始上传...", Toast.LENGTH_LONG).show();


//        uploadUrl = url;
      finishAttach = 0;
      sectionListActivity = sectionList;

      personId = pId;
      totalAttach = fileNames.size();
      if (sectionListActivity.additionalDataChanged){
        totalAttach++;
      }



      uploadTasks = new UploadTask[fileNames.size()];

      for(int i = 0 ; i < fileNames.size() ; i++){
        uploadTasks[i] = new UploadTask(listener);

        uploadTasks[i].execute(getString(R.string.ws_base_url), fileNames.get(i), fileUrls.get(i));
      }

      if (sectionListActivity.additionalDataChanged){

        SharedPreferences pref = sectionListActivity.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);

        updateTask = new UpdateTask(listener);
        updateTask.execute(getString(R.string.ws_base_url), pref.getString("dynamic_info_" + personId,""));
      }


    }

  }

  private NotificationManager getNotificationManager() {
    return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  }

  private Notification getNotification(String title, int progress) {
    Intent intent = new Intent(this, SectionListActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.logo);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo));
    builder.setContentIntent(pi);
    builder.setContentTitle(title);
    if (progress >= 0) {

      builder.setContentText(progress + "%");
      builder.setProgress(100, progress, false);
    }
    return builder.build();
  }
}
